// FontPrint.cpp
#include "FontPrint.h"

char fonttable[] = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
char g_asciitable[256];

void create_asciitable() //Drakonite 4-18-08
{
	memset(&g_asciitable,0,256*sizeof(char));
	for(int i=0;i<256;++i)
	{
		if(fonttable[i]=='\0')
			break;
			
		g_asciitable[int(fonttable[i])]=i;
	}
}

int drawmessage( CAbstractDrawingInterface* dDevice, CAbstractDrawable* fontBuffer, SRect rectDest, char *l_cMessage )
{   
     int glyphWidth = 8;
     int glyphHeight = 8;
     int spaceWidth = 8;
     int tabSize = glyphWidth * 5;
     SRect fontBufferDest = { 0, 0, glyphWidth, glyphHeight };
	 fontBuffer->SetW( glyphWidth );
	 fontBuffer->SetH( glyphHeight );
	 fontBuffer->SetX( rectDest.x );
	 fontBuffer->SetY( rectDest.y );
     
     int lookup;
     int position;
     int failed = (int)strlen(l_cMessage);
     
     for( position = 0; position <= (int)strlen(l_cMessage); position++ )
     {
          if ( l_cMessage[position] == '\n' ) { fontBuffer->SetY( fontBuffer->GetY( ) + glyphHeight ); fontBuffer->SetX( rectDest.x ); }
          else
              if ( l_cMessage[position] == '\t' ) { fontBuffer->SetX( fontBuffer->GetX( ) + tabSize ); }
          else
          {
              lookup = g_asciitable[int(l_cMessage[position])];
              
              switch( lookup )
              {                    
                      case 0x00:
                           if( fontBuffer->GetX() != rectDest.x ) fontBuffer->SetX( fontBuffer->GetX( ) + spaceWidth );
                      break;
                      
                      default:
                           fontBuffer->SetU( ( lookup ) * glyphWidth );
						   dDevice->blit( fontBuffer );
                           fontBuffer->SetX( fontBuffer->GetX( ) + glyphWidth );
              }
              
              if( ( (int)rectDest.w - fontBuffer->GetX( ) ) <= glyphWidth )
              {
                  fontBuffer->SetY( fontBuffer->GetY( ) + glyphHeight );
                  fontBuffer->SetX( rectDest.x );
                
                  if( ( fontBuffer->GetY( ) + glyphHeight ) >= (int)rectDest.w + 1 )
				  {
                      return failed;
				  }
              }
          }
     }
     
     return failed; //0> = Failure, 0< = Undrawable characters, 0 = All complete
}